# src/services/question_service.py
import time
import os
from src.core.factory import ProcessorFactory
from src.api.openai_api import OpenAIClient

def run_processing_pipeline(input_path: str, output_path: str, client: OpenAIClient):
    """
    运行完整的文档处理流水线。
    """
    # 1. 从工厂获取合适的组件
    output_ext = os.path.splitext(output_path)[1]
    
    # 修改：将完整的input_path传递给工厂，让工厂决定使用哪个Reader
    reader = ProcessorFactory.create_reader(input_path)
    writer = ProcessorFactory.create_writer(output_ext)
    splitter = ProcessorFactory.create_splitter()
    llm_processor = ProcessorFactory.create_llm_processor(client)
    
    print("流水线启动...")
    
    # 2. Reader: 读取并转换为 Markdown
    # 这里根据工厂返回的 reader 实例，可能是 WebReader 或 WordReader
    print(f"[{reader.__class__.__name__}] 正在读取: {input_path}")
    markdown_content = reader.read(input_path)
    
    # 3. Splitter: 将 Markdown 分割为问题列表
    print(f"[{splitter.__class__.__name__}] 正在分割问题...")
    questions = splitter.split(markdown_content)
    total_questions = len(questions)
    
    if total_questions == 0:
        print("警告：未发现任何问题，流水线提前结束。")
        writer.write("未能从源文件或URL中提取任何问题。", output_path)
        return

    print(f"共发现 {total_questions} 个问题。")
    
    # 4. LLM Processor: 循环处理每个问题
    processed_answers = []
    for i, question_md in enumerate(questions, 1):
        print(f"[{llm_processor.__class__.__name__}] 正在处理第 {i}/{total_questions} 个问题...")
        try:
            answer_md = llm_processor.process(question_md)
            processed_answers.append(answer_md)
            print(f"第 {i} 个问题处理完成。")
        except Exception as e:
            error_message = f"【问题 {i} 处理失败: {e}】"
            print(error_message)
            processed_answers.append(error_message)
        
        # 控制 API 请求频率
        if i < total_questions:
            wait_time = 20  # 最低等待时间
            print(f"为避免API速率限制，等待 {wait_time} 秒...")
            time.sleep(wait_time)
            
    # 5. 合并所有处理过的 Markdown section
    final_markdown = "\n\n---\n\n".join(processed_answers)
    
    # 6. Writer: 将最终的 Markdown 写入文件
    print(f"[{writer.__class__.__name__}] 正在写入结果到: {output_path}")
    writer.write(final_markdown, output_path)
    
    print(f"流水线处理完成！结果已保存到 {output_path}")